package com.xlongwei.todays.config;

import java.util.Collections;
import java.util.List;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.data.cache.CacheService;
import org.noear.solon.data.cache.EmptyCacheService;
import org.noear.solon.data.cache.LocalCacheService;
import org.smartboot.http.common.utils.NumberUtils;
import cn.dev33.satoken.solon.integration.SaTokenInterceptor;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpInterfaceDefaultImpl;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
public class AppConfig {
    public static final boolean enableCache =
            Boolean.parseBoolean(Solon.cfg().get("solon.cache.enable", "true"));
    public static final int defSeconds =
            Math.max(30, NumberUtils.toInt(Solon.cfg().get("solon.cache.defSeconds"), 3600));

    /**
     * <pre>
     * 注意顺序：LoggingRouterInterceptor记日志-30 > AppRouterInterceptor捕异常-20 > SaTokenInterceptor 验登录-10
     * </pre>
     */
    @Bean(index = -10) // -100，是顺序位（低值优先）
    public SaTokenInterceptor saTokenInterceptor() {
        // 必须addInclude匹配，否则不会检查@SaCheckLogin，路径匹配但是没有注解也不会拦截/user/login，排除路径可以addExclude
        return new SaTokenInterceptor().addInclude("/**"); // 用于支持规划处理及注解处理
    }

    @Bean
    public StpInterface stpInterface() {
        List<String> EMPTY = Collections.emptyList(), ADMIN = Collections.singletonList("admin");
        return new StpInterfaceDefaultImpl() {
            @Override
            public List<String> getRoleList(Object loginId, String loginType) {
                return "1".equals(loginId) ? ADMIN : EMPTY;
            }
        };
    }

    @Bean
    public CacheService cacheService() {
        return enableCache ? new LocalCacheService(defSeconds) : new EmptyCacheService();
    }

}
